<template>
  <div f-c-c text-18 cursor-pointer @click="handleSwitch">
    <icon-mdi-moon-waning-crescent v-if="themeStore.darkMode" />
    <icon-mdi-white-balance-sunny v-else />
  </div>
</template>

<script setup lang="ts">
import { useThemeStore } from "@/store";

const themeStore = useThemeStore();

const handleSwitch = async (event: MouseEvent) => {
  const x = event.clientX;
  const y = event.clientY;

  if (!document.startViewTransition) return;

  const endRadius = Math.hypot(
    Math.max(x, innerWidth - x),
    Math.max(y, innerHeight - y)
  );

  const transition = document.startViewTransition(() => {
    themeStore.toggleDarkMode();
  });

  await transition.ready;

  const clipPath = [
    `circle(0px at ${x}px ${y}px)`,
    `circle(${endRadius}px at ${x}px ${y}px)`,
  ];

  document.documentElement.animate(
    {
      clipPath: themeStore.darkMode ? clipPath : [...clipPath].reverse(),
    },
    {
      duration: 300,
      easing: "ease-in",
      pseudoElement: themeStore.darkMode
        ? "::view-transition-new(root)"
        : "::view-transition-old(root)",
    }
  );
};
</script>

<style>
::view-transition-old(root),
::view-transition-new(root) {
  animation: none;
  mix-blend-mode: normal;
}
::view-transition-old(root) {
  z-index: 9999;
}
::view-transition-new(root) {
  z-index: 1;
}
.dark::view-transition-old(root) {
  z-index: 1;
}
.dark::view-transition-new(root) {
  z-index: 9999;
}
</style>
